//
//  JKRRecommendViewController.m
//  百思不得姐
//
//  Created by Lucky on 16/2/29.
//  Copyright © 2016年 Lucky. All rights reserved.
//

#import "JKRRecommendViewController.h"
#import "JKRRecommendCategoryCellTableViewCell.h"
#import "JKRRecommendUserTableViewCell.h"
#import "JKRRecommendCategory.h"
#import "JKRRecommentUser.h"
#import <MJRefresh.h>

#define JKRSelectedCategory self.categories[self.leftTableView.indexPathForSelectedRow.row]

@interface JKRRecommendViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *leftTableView;

@property (nonatomic, strong) UITableView *rightTableView;

@property (nonatomic, strong) NSArray *categories;

/** 请求参数 */
@property (nonatomic, strong) NSMutableDictionary *params;

/** AFN请求管理者 */
@property (nonatomic, strong) AFHTTPSessionManager *manager;

@end

@implementation JKRRecommendViewController

static NSString *const leftIdenfifier = @"recommendLeftCell";
static NSString *const rightIdenfifier = @"recommendRigthCell";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"推荐关注";
    
    self.view.backgroundColor = JKRGlobalBackgroudColor;
    
    [self.view addSubview:self.leftTableView];
    [self.view addSubview:self.rightTableView];
    [self setChildViewsLayout];
    
    [self setupRefresh];
    
    [self loadCatagories];
    
}

#pragma mark - 网络数据获取

- (void)loadCatagories
{
    [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeBlack];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = @"category";
    params[@"c"] = @"subscribe";
    [self.manager GET:@"http://api.budejie.com/api/api_open.php" parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [SVProgressHUD dismiss];
        self.categories = [JKRRecommendCategory mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        [self.leftTableView reloadData];
        [self.leftTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:UITableViewScrollPositionTop];
        
        [self.rightTableView.mj_header beginRefreshing];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD showErrorWithStatus:@"加载推荐信息失败!"];
    }];
}

- (void)setupRefresh
{
    self.rightTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewUsers)];
    
    self.rightTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreUsers)];
    
}

- (void)loadNewUsers
{
    JKRRecommendCategory *selectedCategory = JKRSelectedCategory;
    
    selectedCategory.currentPage = 1;
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = @"list";
    params[@"c"] = @"subscribe";
    params[@"category_id"] = @(selectedCategory.id);
    params[@"page"] = @(selectedCategory.currentPage);
    
    self.params = params;
    
    [self.manager GET:@"http://api.budejie.com/api/api_open.php" parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSArray *users = [JKRRecommentUser mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        
        NSLog(@"%@", responseObject);
        
        [selectedCategory.users removeAllObjects];
        
        [selectedCategory.users addObjectsFromArray:users];
        
        selectedCategory.total = [responseObject[@"total"] integerValue];
        
        if (self.params != params) return;
        
        [self.rightTableView reloadData];
        
        [self.rightTableView.mj_header endRefreshing];
        
        [self checkFooterState];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (self.params != params) return;
        
        [SVProgressHUD showErrorWithStatus:@"加载用户数据失败!"];
        
        [self.rightTableView.mj_header endRefreshing];
    }];
}

- (void)loadMoreUsers
{
    JKRRecommendCategory *selectedCategory = JKRSelectedCategory;
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = @"list";
    params[@"c"] = @"subscribe";
    params[@"category_id"] = @(selectedCategory.id);
    params[@"page"] = @(++selectedCategory.currentPage);
    
    self.params = params;
    
    [self.manager GET:@"http://api.budejie.com/api/api_open.php" parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSArray *users = [JKRRecommentUser mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        
        [selectedCategory.users addObjectsFromArray:users];
        
        if (self.params != params) return;
        
        [self.rightTableView reloadData];
        
        [self checkFooterState];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (self.params != params) return;
        
        [SVProgressHUD showErrorWithStatus:@"加载用户数据失败!"];
        
        [self.rightTableView.mj_footer endRefreshing];
    }];
}

- (void)checkFooterState
{
    JKRRecommendCategory *rc = JKRSelectedCategory;
    
    self.rightTableView.mj_footer.hidden = (rc.users.count == 0);
    
    if (rc.users.count == rc.total) {
        [self.rightTableView.mj_footer endRefreshingWithNoMoreData];
    }else{
        [self.rightTableView.mj_footer endRefreshing];
    }
}

#pragma mark - tableView数据源和代理

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.leftTableView) {
        return self.categories.count;
    }else{
        [self checkFooterState];
        JKRRecommendCategory *category = self.categories[self.leftTableView.indexPathForSelectedRow.row];
        return category.users.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.leftTableView) {
        JKRRecommendCategoryCellTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:leftIdenfifier forIndexPath:indexPath];
        cell.model = self.categories[indexPath.row];
        
        return cell;
    }else {
        JKRRecommendUserTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:rightIdenfifier forIndexPath:indexPath];
        
        JKRRecommendCategory *category = self.categories[self.leftTableView.indexPathForSelectedRow.row];
        JKRRecommentUser *user = category.users[indexPath.row];
        
        cell.model = user;
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.leftTableView) {
        return [JKRRecommendCategoryCellTableViewCell heightWithModel:self.categories[indexPath.row]];
    }else{
        JKRRecommendCategory *category = self.categories[self.leftTableView.indexPathForSelectedRow.row];
        JKRRecommentUser *user = category.users[indexPath.row];
        return [JKRRecommendUserTableViewCell heightWithModel:user];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.leftTableView) {
        [self.rightTableView.mj_header endRefreshing];
        [self.rightTableView.mj_footer endRefreshing];
        
        JKRRecommendCategory *category = self.categories[indexPath.row];
        
        if (category.users.count) {
            [self.rightTableView reloadData];
        }else {
            
            [self.rightTableView reloadData];
            
            [self.rightTableView.mj_header beginRefreshing];
            
        }
    }
}

#pragma mark - 初始化设置和懒加载

- (void)setChildViewsLayout
{
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    [self.leftTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mas_topLayoutGuideBottom);
        make.leading.equalTo(self.view);
        make.width.equalTo(self.view).multipliedBy(0.3);
        make.bottom.equalTo(self.mas_bottomLayoutGuideTop);
    }];
    
    [self.rightTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mas_topLayoutGuideBottom);
        make.leading.equalTo(self.leftTableView.mas_trailing);
        make.trailing.equalTo(self.view);
        make.bottom.equalTo(self.mas_bottomLayoutGuideTop);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

- (UITableView *)leftTableView
{
    if (!_leftTableView) {
        _leftTableView = [[UITableView alloc] init];
        _leftTableView.backgroundColor = JKRColor(244, 244, 244, 1.0);
        _leftTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _leftTableView.dataSource = self;
        _leftTableView.delegate = self;
        [_leftTableView registerClass:[JKRRecommendCategoryCellTableViewCell class] forCellReuseIdentifier:leftIdenfifier];
    }
    return _leftTableView;
}

- (UITableView *)rightTableView
{
    if (!_rightTableView) {
        _rightTableView = [[UITableView alloc] init];
        _rightTableView.backgroundColor = [UIColor whiteColor];
        _rightTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _rightTableView.dataSource = self;
        _rightTableView.delegate = self;
        [_rightTableView registerClass:[JKRRecommendUserTableViewCell class] forCellReuseIdentifier:rightIdenfifier];
    }
    return _rightTableView;
}

- (AFHTTPSessionManager *)manager
{
    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}

#pragma mark - 控制器销毁
- (void)dealloc
{
    [self.manager.operationQueue cancelAllOperations];
}

@end
